package com.wframe.project.jnd.wx.controller;

import com.frame.database.JdataBean;
import com.wframe.framework.spring.SpringContextHolder;
import com.wframe.project.jnd.rest.util.ClientException;
import com.wframe.project.jnd.rest.util.JsonReturn;
import com.wframe.project.jnd.rest.util.SessionUser;
import com.wframe.project.jnd.rest.util.WebSession;
import com.wframe.project.jnd.services.CouponService;
import com.wframe.project.jnd.services.UserService;
import com.wframe.project.jnd.util.WebUtils;
import com.wframe.project.jnd.vo.Coupon;
import com.wframe.project.jnd.wx.constant.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by lwb on 2017/4/15.
 */
@Controller
@RequestMapping("/we/coupon")
public class WechatCouponController extends BaseController {

    private static final String REDIS_NUM_KEY = "REDIS_NUM";
    private static final String REDIS_SALES_KEY = "REDIS_SALES";
    private static final String REDIS_AMOUNT_KEY = "REDIS_AMOUNT";
    private static final String REDIS_LIMIT_NUM_KEY = "REDIS_LIMIT_NUM";

    @Autowired
    private CouponService couponService;

    /**
     * 可使用的优惠券列表
     *
     * @param orderCode
     * @param ordermoney
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/{orderCode}", method = RequestMethod.GET)
    public String loadcanlist(@PathVariable("orderCode") String orderCode,
                              @RequestParam("ordermoney") Double ordermoney,
                              @RequestParam("bz") String orderbz,
                              @RequestParam("paytype") String paytype,
                              Model model) {
        SessionUser sessionUser = WebSession.getWbUser(session);
        if (sessionUser == null) {
            return "redirect:/we/user/login";
        }

        String userId = sessionUser.getUserid();
        if (!WebSession.checkWbUserAuth(userId)) {
            return "redirect:/we/message";
        }

        List<Map> list = couponService.findCanCouponList(userId, ordermoney, UserService.UserSourceEnum.WECHAT.ordinal());
        List<Map> dlist = new ArrayList<>();
        for (Map bean : list) {
            JdataBean data = new JdataBean();
            data.put("id", WebUtils.aesEncode(bean.get("id").toString()));//id加密
            data.put("offer_money", bean.get("offer_money"));
            data.put("min_money", bean.get("min_money"));
            data.put("enddate", bean.get("enddate"));
            data.put("name",bean.get("name"));
            data.put("startdate",bean.get("startdate"));
            dlist.add(data.getDataMap());
        }

        model.addAttribute("list", dlist);
        model.addAttribute("code", orderCode);
        model.addAttribute("orderbz", orderbz);
        model.addAttribute("paytype", paytype);
        model.addAttribute("ordermoney", ordermoney);

        return "/wesite/view/home/check-coupon";
    }

    /**
     * 选择优惠券
     *
     * @param ordercode
     * @return
     */
    @RequestMapping(value = "/{orderCode}", method = RequestMethod.PUT)
    @ResponseBody
    public String chooseCoupon(@PathVariable("orderCode") String ordercode,
                               @RequestParam(value = "couponId", required = false) String couponId,
                               @RequestParam("offerMoney") String offerMoney,
                               @RequestParam("bz") String orderbz,
                               @RequestParam("paytype") String paytype) {
        Map<String, Object> orderMap = new HashMap<>();

        orderMap.put("orderbz", orderbz);
        orderMap.put("paytype", paytype);
        if (couponId != null && !"0".equalsIgnoreCase(couponId)) {
            orderMap.put("couponId", couponId);
            orderMap.put("offerMoney", offerMoney);
        }

        session.setAttribute(ordercode, orderMap);

        return new JsonReturn().toString("/we/order/" + ordercode);
    }

    /**
     * 领取优惠券
     *
     * @param couponId
     * @return
     * @throws ClientException
     */
    @RequestMapping(value = "/receive/{id}", method = RequestMethod.POST)
    @ResponseBody
    public String addCoupon(@PathVariable("id") Integer couponId) throws Exception {
        JsonReturn json = new JsonReturn();
        String userId = WebSession.getUserId(session);
        JdataBean coupon = couponService.findOne(userId, couponId, UserService.UserSourceEnum.WECHAT.ordinal());
        if (coupon != null && coupon.getInt("limit_num") > coupon.getInt("num")) {
            json.putData(coupon.getInt("amount") > (coupon.getInt("sales") + 1) && coupon.getInt("limit_num") > (coupon.getInt("num") + 1));
            couponService.receiveCoupon(coupon, userId, Constant.COUPON_SOURCE_ACQUIRE);
        }

        return json.toString();
    }


}
